package com.opc.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.opc.entity.ConsumeStatistic;
import com.opc.mapper.ConsumeStatisticMapper;
import com.opc.service.ConsumeStatisticService;
import com.opc.utils.DateUtils;
import com.opc.utils.StringUtils;
import org.ehcache.impl.internal.concurrent.ConcurrentHashMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 作者
 * @since 2023-04-03
 */
@Service
public class ConsumeStatisticServiceImpl extends ServiceImpl<ConsumeStatisticMapper, ConsumeStatistic> implements ConsumeStatisticService {

    @Autowired
    private ConsumeStatisticMapper statisticMapper;

    @Override
    public Map<String, List<Object>> getStatisticListMonth(Integer type, String proLine, String stationNum, String deviceCode) {
        Map<String, List<Object>> map = new HashMap<>();
        List<Object> dayList = new ArrayList<>();
        List<Object> dataList = new ArrayList<>();
        Date nowTime = new Date();
        DateTime startTime = DateUtil.beginOfMonth(nowTime);
        DateTime endTime = DateUtil.endOfMonth(nowTime);
        List<String> dayArray = DateUtils.getDayList(startTime, endTime, "yyyy-MM-dd");
        for (int i = 1; i <= dayArray.size(); i++) {
            dayList.add(i);
        }
        map.put("dayList", dayList);
        Map<String, Object> paramsMap = new ConcurrentHashMap<>();
        paramsMap.put("startTime", startTime);
        paramsMap.put("endTime", endTime);
        paramsMap.put("type", type);
        if (!StringUtils.isBlank(proLine)) {
            paramsMap.put("proLine", proLine);
        }
        if (!StringUtils.isBlank(stationNum)) {
            paramsMap.put("stationNum", stationNum);
        }
        if (!StringUtils.isBlank(deviceCode)) {
            paramsMap.put("deviceCode", deviceCode);
        }
        List<ConsumeStatistic> list = statisticMapper.getStatisticListMonth(paramsMap);
        if (list == null || list.isEmpty()) {
            for (int i = 1; i <= dayArray.size(); i++) {
                dataList.add(0);
            }
            map.put("list", dataList);
            return map;
        }
        Map<String, Long> sMap = new HashMap<>();
        for (ConsumeStatistic s : list) {
            sMap.put(DateUtil.format(s.getStatisticTime(), "yyyy-MM-dd"), s.getConsumeVal());
        }
        for (String day : dayArray) {
            if (sMap.containsKey(day)) {
                dataList.add(sMap.get(day));
                continue;
            }
            dataList.add(0);
        }
        map.put("list", dataList);
        return map;
    }
}
